package com.talkyun.utils;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

public class UrlFetch {

    protected Logger logger = LoggerFactory.getLogger(UrlFetch.class);

    public String fetch(String url) {
        try {
            return fetch(new URL(url));
        } catch (MalformedURLException e) {
            throw new RuntimeException("Can't fetch " + url, e);
        }
    }

    public String fetch(URL url) {
        InputStream ins = null;
        try {
            ins = url.openStream();
            return this.readStream(ins);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            this.close(ins);
        }
    }

    private String readStream(InputStream ins) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream(1024 * 4);
        byte[] buf = new byte[1024];
        int num = ins.read(buf);
        while (num != -1) {
            baos.write(buf, 0, num);
            num = ins.read(buf);
        }
        return baos.toString("utf-8");
    }

    private void close(Closeable cls) {
        try {
            if (cls != null) {
                cls.close();
            }
        } catch (IOException e) {
            // ignore
            logger.error("Close stream!", e);
        }
    }
}